/*
 token.go
 Created by hupfei on 2019-10-17
*/

package v1

import (
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"github.com/pkg/errors"
	"strconv"
	"zimuzu_cvn_web_api/config"
	"zimuzu_cvn_web_api/model"
	"zimuzu_cvn_web_api/pkg/e"
	"zimuzu_cvn_web_api/pkg/errno"
	"zimuzu_cvn_web_api/router/api"
	"zimuzu_cvn_web_api/router/api/app/middleware"
	"zimuzu_cvn_web_api/service"
	"zimuzu_cvn_web_api/service/flows"
)

type TokenAPI struct {
}

func (a TokenAPI) Name() string {
	return "token API"
}

func (a TokenAPI) Bind() {
	tokenAPI := config.C.Router.Group("/v1/app/token", middleware.TrackLog())
	{
		tokenAPI.GET("superNodeList", superNodeList)
		tokenAPI.GET("cancelPledge", cancelPledge)
	}

	tokenAuthAPI := config.C.Router.Group("/v1/app/token", middleware.TrackLog(), middleware.AuthMiddleware())
	{
		tokenAuthAPI.GET("userInfo", tokenUserInfo)
		tokenAuthAPI.GET("buyBackRankInfo", buyBackRankInfo)
		tokenAuthAPI.GET("nodeList", nodeList)
		tokenAuthAPI.GET("tokenList", tokenList)
		tokenAuthAPI.GET("tokenNodeList", tokenNodeList)
		tokenAuthAPI.GET("pledge", tokenPledge)
		tokenAuthAPI.GET("refreshNodeInfo", refreshNodeInfo)
		tokenAuthAPI.GET("saleOrderList", saleOrderList)
		tokenAuthAPI.GET("rentOrderList", rentOrderList)
		tokenAuthAPI.GET("depositInfo", depositInfo)
		tokenAuthAPI.GET("depositList", depositList)
		tokenAuthAPI.GET("platformTradeStepFirst", platformTradeStepFirst)
		tokenAuthAPI.POST("platformTradeStepSecond", platformTradeStepSecond)
		tokenAuthAPI.POST("platformTradePay", platformTradePay)
		tokenAuthAPI.GET("tradeList", tradeList)
		tokenAuthAPI.GET("outsideTradeStepFirst", outsideTradeStepFirst)
		tokenAuthAPI.POST("outsideTradeStepSecond", outsideTradeSetpSecond)
		tokenAuthAPI.POST("outsideTradePay", outsideTradePay)
		tokenAuthAPI.GET("buyTradeInfo", buyTradeInfo)
		tokenAuthAPI.GET("buybackStepFirst", buybackStepFirst)
		tokenAuthAPI.POST("buybackStepSecond", buybackStepSecond)
		tokenAuthAPI.POST("buybackStepThird", buybackStepThird)
		tokenAuthAPI.GET("selfNum", selfNum)
		tokenAuthAPI.POST("issueOrder", issueOrder)
		tokenAuthAPI.GET("sellTradeInfo", sellTradeInfo)
		tokenAuthAPI.POST("saleOrderCancel", saleOrderCancel)
		tokenAuthAPI.GET("mySaleTradeList", mySaleTradeList)
		tokenAuthAPI.GET("myBuyBackQueue", myBuyBackQueue)
		tokenAuthAPI.POST("buyBackRankCancel", buyBackRankCancel)

		tokenAuthAPI.GET("rentSquare", rentSquare)
		tokenAuthAPI.GET("rentMyOrder", rentMyOrder)
		tokenAuthAPI.GET("rentOrderDetail", rentOrderDetail)
		tokenAuthAPI.POST("rentToken", rentToken)
		tokenAuthAPI.POST("rentSubmitOrder", rentSubmitOrder)
		tokenAuthAPI.GET("rentCancelOrder", rentCancelOrder)
		tokenAuthAPI.GET("rentViolationNum", rentViolationNum)
		tokenAuthAPI.GET("rentCheckDeposit", rentCheckDeposit)
		tokenAuthAPI.GET("notRentNum", notRentNum)
		tokenAuthAPI.GET("minerAverageRevenue", minerAverageRevenue)
	}
}

/*
 * @ Author: hupfei
 * @ Description: 3.1.1超级节点列表
 **/
func superNodeList(c *gin.Context) {
	info, err := service.GetSuperNodeList()
	if err != nil {
		api.SendResponse(c, errors.New("请求超级节点列表失败"), nil)
		return
	}

	errno.OK.Info = "成功"
	api.SendResponse(c, errno.OK, info)
	return
}

/*
 * @ Author: hupfei
 * @ Description: 3.1.2用户信息
 **/
func tokenUserInfo(c *gin.Context) {

	uid, _ := service.GetUserIdByRequest(c)
	info, err := service.TokenUserInfo(uid)
	if err != nil {
		api.SendResponse(c, errors.New("查询用户信息失败"), nil)
		return
	}

	errno.OK.Info = "成功"
	api.SendResponse(c, errno.OK, info)
	return
}

type refreshNodeInfoParams struct {
	Type int `form:"type" binding:"required"`
}

func refreshNodeInfo(c *gin.Context) {
	var params refreshNodeInfoParams
	err := c.ShouldBindQuery(&params)
	if err != nil {
		api.SendResponse(c, errno.ParamsError, nil)
		return
	}
	uid, _ := service.GetUserIdByRequest(c)
	res := service.GetNodeInfo(uid, params.Type)
	errno.OK.Info = "成功"
	api.SendResponse(c, errno.OK, res)
	return
}

/*
 * @ Author: hupfei
 * @ Description: 3.1.3节点列表
 **/
type nodeListParams struct {
	model.PageParams
	Type int `form:"type"`
}

func nodeList(c *gin.Context) {
	var params nodeListParams
	params.PageParams = model.NewDefaultPageParams()
	err := c.ShouldBindQuery(&params)
	if err != nil {
		api.SendResponse(c, errno.ParamsError, nil)
		return
	}
	uid, _ := service.GetUserIdByRequest(c)
	res, err := model.GetNodeList(uid, params.Type, params.Per, params.Page)
	if err != nil {
		api.SendResponse(c, errors.New("请求失败"), nil)
		return
	}
	errno.OK.Info = "成功"
	api.SendResponse(c, errno.OK, res)
	return
}

/*
 * @ Author: hupfei
 * @ Description: 3.1.4质押令牌/撤销质押
 **/
type tokenPledgeParams struct {
	Source    int `form:"source"`                  //0 质押  1撤销质押
	Type      int `form:"type" binding:"required"` //1 pc  2 linux  3 router
	TokenType int `form:"tokenType"`               //0 租用令牌  1 自有令牌
	NodeId    int `form:"nodeId"`                  //节点id，批量质押/撤销时传0
}

func tokenPledge(c *gin.Context) {
	var params tokenPledgeParams
	err := c.ShouldBindQuery(&params)
	if err != nil {
		api.SendResponse(c, errno.ParamsError, nil)
		return
	}
	uid, _ := service.GetUserIdByRequest(c)
	err = service.TokenPledge(uid, params.Source, params.TokenType, params.Type, params.NodeId)
	if err != nil {
		api.SendResponse(c, err, nil)
		return
	}
	if params.Source == 0 {
		errno.OK.Info = "质押成功"
	} else {
		errno.OK.Info = "撤销质押成功"
	}
	flows.DeleteUserNodeListKey(uid)
	api.SendResponse(c, errno.OK, nil)
	return
}

type cancelPledgeParams struct {
	Uid    int64  `form:"uid" binding:"required"`
	NodeId int    `form:"nodeId" binding:"required"` //节点id
	T      int    `form:"t" binding:"required"`      //当前时间戳
	Sign   string `form:"sign" binding:"required"`   //md5(api_key+t+uid+nodeId)
}

/*
 * @ Author: hupfei
 * @ Description: 撤销质押
 **/
func cancelPledge(c *gin.Context) {
	var params cancelPledgeParams
	err := c.ShouldBindQuery(&params)
	if err != nil {
		api.SendResponse(c, errno.ParamsError, nil)
		return
	}

	//判断签名是否正确
	e.Log("info", "Sign=", params.Sign)
	e.Log("info", "Md5Str Sign=", e.Md5Str(config.C.ApiKey+strconv.Itoa(params.T)+strconv.FormatInt(params.Uid, 10)+strconv.Itoa(params.NodeId)))
	if params.Sign != e.Md5Str(config.C.ApiKey+strconv.Itoa(params.T)+strconv.FormatInt(params.Uid, 10)+strconv.Itoa(params.NodeId)) {
		api.SendResponse(c, errors.New("非法请求"), nil)
		return
	}

	nodeInfo, err := model.GetNodePledgeInfoByNodeId(params.NodeId)
	if err != nil {
		api.SendResponse(c, errors.New("节点不存在"), nil)
		return
	}

	if nodeInfo.Status == 1 {
		errno.OK.Info = "撤销质押成功(该节点并未质押)"
		api.SendResponse(c, errno.OK, nil)
		return
	}

	err = service.CancelPledge(params.Uid, params.NodeId)
	if err != nil {
		api.SendResponse(c, err, nil)
		return
	}
	errno.OK.Info = "撤销质押成功"
	flows.DeleteUserNodeListKey(params.Uid)
	api.SendResponse(c, errno.OK, nil)
	return
}

type tokenOrderListParams struct {
	model.PageParams
	Source int `form:"source"` //0购买 1出售/0借入 1借出
}

/*
 * @ Author: hupfei
 * @ Description:3.1.5购买/出售详情
 **/
func saleOrderList(c *gin.Context) {
	var params tokenOrderListParams
	params.PageParams = model.NewDefaultPageParams()
	err := c.ShouldBindQuery(&params)
	if err != nil {
		api.SendResponse(c, errno.ParamsError, nil)
		return
	}
	uid, _ := service.GetUserIdByRequest(c)
	res, err := model.GetSaleOrderList(uid, params.Source, params.Per, params.Page)
	if err != nil {
		api.SendResponse(c, errors.New("请求失败"), nil)
		return
	}
	errno.OK.Info = "成功"
	api.SendResponse(c, errno.OK, res)
	return
}

/*
 * @ Author: hupfei
 * @ Description:3.1.6借入/借出详情
 **/
func rentOrderList(c *gin.Context) {
	var params tokenOrderListParams
	params.PageParams = model.NewDefaultPageParams()
	err := c.ShouldBindQuery(&params)
	if err != nil {
		api.SendResponse(c, errno.ParamsError, nil)
		return
	}
	uid, _ := service.GetUserIdByRequest(c)
	res, err := model.GetSellOrderList(uid, params.Source, params.Per, params.Page)
	if err != nil {
		api.SendResponse(c, errors.New("请求失败"), nil)
		return
	}

	if params.Source == 1 {
		for k, v := range res {
			if v.OrderStatus == model.TokenRentOrderStatusComplete {
				//借出需要判断保证金是否充足
				checkData, _ := service.CheckRentTokenPledgeStatus(v.Uid, 0)
				if checkData.Status == 2 {
					res[k].Status = "有"
				} else {
					res[k].Status = "无"
				}
			} else if v.OrderStatus == model.TokenRentOrderStatusEnd {
				res[k].Status = "已归还"
			} else if v.OrderStatus == model.TokenRentOrderStatusStop {
				res[k].Status = "提前归还"
			}
		}
	}

	errno.OK.Info = "成功"
	api.SendResponse(c, errno.OK, res)
	return
}

/*
 * @ Author: hupfei
 * @ Description:3.1.8增加、提取保证金信息
 **/
func depositInfo(c *gin.Context) {
	uid, _ := service.GetUserIdByRequest(c)
	cvntAmount, err := service.GetUserCvnAmountByUid(uid)
	if err != nil {
		api.SendResponse(c, errors.New("查询账户信息失败"), nil)
		return
	}
	res := make(map[string]interface{})
	//可用余额
	res["availableCvnt"] = cvntAmount.Balance
	//不可用的保证金
	checkData, err := service.CheckRentTokenPledgeStatus(uid, 0)
	if err != nil {
		api.SendResponse(c, errors.New("请求失败"), nil)
		return
	}
	res["unavailableDepositCvnt"] = checkData.TotalCvn
	res["requiredDepositCvnt"] = 0.00
	//需要增加的保证金
	if checkData.Status == 2 {
		if checkData.Cvn < 0 {
			api.SendResponse(c, errors.New("账户可用余额不足"), nil)
			return
		}
		res["requiredDepositCvnt"] = checkData.NeedCvn
	}

	errno.OK.Info = "ok"
	api.SendResponse(c, errno.OK, res)
	return
}

/*
 * @ Author: hupfei
 * @ Description:3.1.9保证金明细
 **/
func depositList(c *gin.Context) {
	var params = model.NewDefaultPageParams()
	err := c.ShouldBindQuery(&params)
	if err != nil {
		api.SendResponse(c, errno.ParamsError, nil)
		return
	}

	uid, _ := service.GetUserIdByRequest(c)
	list, err := model.GetDepositLogList(uid, params.Per, params.Page)
	if err != nil {
		api.SendResponse(c, errors.New("请求失败"), nil)
		return
	}
	errno.OK.Info = "ok"
	api.SendResponse(c, errno.OK, list)
	return
}

/*
 * @ Author: hupfei
 * @ Description:3.1.11令牌列表
 **/
func tokenList(c *gin.Context) {
	var params = model.NewDefaultPageParams()
	err := c.ShouldBindQuery(&params)
	if err != nil {
		api.SendResponse(c, errno.ParamsError, nil)
		return
	}
	uid, _ := service.GetUserIdByRequest(c)

	list, err := model.GetRouterTokenList(uid, params.Per, params.Page)
	if err != nil {
		api.SendResponse(c, errors.New("请求失败"), nil)
		return
	}
	errno.OK.Info = "ok"
	api.SendResponse(c, errno.OK, list)
	return
}

/*
 * @ Author: hupfei
 * @ Description:3.1.12令牌下的节点列表
 **/
type tokenNodeListParams struct {
	TokenId int `form:"tokenId" binding:"required"`
}

type tokenNodeListRes struct {
	NodeId int    `json:"node_id" db:"node_id"`
	Name   string `json:"name" db:"name"`
}

func tokenNodeList(c *gin.Context) {
	var params tokenNodeListParams
	err := c.ShouldBindQuery(&params)
	if err != nil {
		api.SendResponse(c, errno.ParamsError, nil)
		return
	}
	uid, _ := service.GetUserIdByRequest(c)
	list, err := model.GetNodeListWithTokenId(params.TokenId, uid)
	if err != nil {
		api.SendResponse(c, errors.New("请求失败"), nil)
		return
	}

	res := make([]tokenNodeListRes, len(list))
	for k, v := range list {
		res[k].NodeId = v.NodeId
		res[k].Name = v.Name
	}

	errno.OK.Info = "ok"
	api.SendResponse(c, errno.OK, res)
	return
}

//官方渠道购买第一步（填写数量）
//Auth: Xu
func platformTradeStepFirst(c *gin.Context) {

	// 官方购买不支持 Date:2020-05-11
	api.SendResponse(c, errors.New("暂不支持"), nil)
	return

	uid, _ := service.GetUserIdByRequest(c)
	cvnAmount, err := service.GetUserCvnAmountByUid(uid)
	if err != nil {
		api.SendResponse(c, errors.New("查询账户信息失败"), nil)
		return
	}

	returnData := make(map[string]interface{})
	returnData["usableCvnt"] = cvnAmount.Balance

	price := service.GetCurrentTokenCvntPrice(0)
	returnData["unitPrice"] = price

	errno.OK.Info = "ok"
	api.SendResponse(c, errno.OK, returnData)
	return
}

type platformTradeSetpSenondParams struct {
	Num int `form:"num" json:"num" binding:"required"`
}

//官方渠道购买第二步（下单）
//Auth: Xu
func platformTradeStepSecond(c *gin.Context) {
	// 检查参数是否为空
	var params platformTradeSetpSenondParams
	err := c.ShouldBindWith(&params, binding.FormPost)
	if err != nil {
		api.SendResponse(c, err, nil)
		return
	}
	uid, _ := service.GetUserIdByRequest(c)
	err, returnData := service.PlatformTradeCreateOrder(uid, params.Num)
	if err != nil {
		api.SendResponse(c, err, nil)
		return
	}

	errno.OK.Info = "ok"
	api.SendResponse(c, errno.OK, returnData)
	return

}

type platformTradePayParams struct {
	OrderNo string `form:"orderNo" json:"orderNo" binding:"required,excludes=  "`
	Code    int    `form:"code" json:"code" `
	U       string `form:"u" json:"u" binding:"required,excludes= "`
}

//官方渠道购买第三步（支付）
//Auth: Xu
func platformTradePay(c *gin.Context) {
	var params platformTradePayParams
	err := c.ShouldBindWith(&params, binding.FormPost)
	if err != nil {
		api.SendResponse(c, errno.ParamsError, nil)
		return
	}
	uid, _ := service.GetUserIdByRequest(c)
	userInfo, err := service.GetUserInfo(uid)
	if err != nil {
		api.SendResponse(c, err, nil)
		return
	}
	ok := service.IsPayPasswordChecked(uid, params.U)
	if !ok {
		api.SendResponse(c, errno.SignError, nil)
		return
	}
	if errValid := service.ValidateCode(userInfo.PhoneNumber, service.SendCodeScenetokenBuy, params.Code); errValid != nil {
		api.SendResponse(c, errValid, nil)
		return
	}
	err = service.PayTokenSaleOrder(params.OrderNo, uid)
	if err != nil {
		api.SendResponse(c, err, nil)
		return
	}
	//重置验证码
	service.DeleteCodeCahce(userInfo.PhoneNumber, service.SendCodeScenetokenBuy)

	errno.OK.Info = "支付成功"
	api.SendResponse(c, errno.OK, nil)
	return

}

//第三方在售订单列表
//Auth: Xu
func tradeList(c *gin.Context) {
	var params = model.NewDefaultPageParams()
	err := c.ShouldBindWith(&params, binding.Query)
	if err != nil {
		api.SendResponse(c, err, nil)
		return
	}
	returnData, err := service.GetSalingOrderList(params.Per, params.Page)
	if err != nil {
		api.SendResponse(c, err, nil)
		return
	}

	errno.OK.Info = "ok"
	api.SendResponse(c, errno.OK, returnData)
	return
}

//三方渠道购买第一步（填写数量）
//Auth: Xu
func outsideTradeStepFirst(c *gin.Context) {
	api.SendResponse(c, errno.FunctionClose, nil)
	return

	uid, _ := service.GetUserIdByRequest(c)
	usdtAmount, err := service.GetUserUsdtAmountByUid(uid)
	if err != nil {
		api.SendResponse(c, err, nil)
		return
	}

	data := make(map[string]interface{})
	data["usableUsdt"] = usdtAmount.Balance

	errno.OK.Info = "ok"
	api.SendResponse(c, errno.OK, data)
	return

}

type outsideTradeSetpSecondParams struct {
	Num     int    `form:"num" json:"num" binding:"required"`
	OrderNo string `form:"orderNo" json:"orderNo" binding:"required"`
}

//三方渠道购买第二步（下单）
//Auth: Xu
func outsideTradeSetpSecond(c *gin.Context) {
	api.SendResponse(c, errno.FunctionClose, nil)
	return

	// 检查参数是否为空
	var params outsideTradeSetpSecondParams
	err := c.ShouldBindWith(&params, binding.FormPost)
	if err != nil {
		api.SendResponse(c, err, nil)
		return
	}
	uid, _ := service.GetUserIdByRequest(c)
	retrunData, err := service.OutsideTradeCreateOrder(params.OrderNo, params.Num, uid)
	if err != nil {
		api.SendResponse(c, err, nil)
		return
	}

	errno.OK.Info = "ok"
	api.SendResponse(c, errno.OK, retrunData)
	return

}

type outsideTradePayParams struct {
	OrderNo string `form:"orderNo" json:"orderNo" binding:"required,excludes=  "`
	Code    int    `form:"code" json:"code"`
	U       string `form:"u" json:"u" binding:"required,excludes= "`
}

//三方渠道购买第三步（支付）
//Auth: Xu
func outsideTradePay(c *gin.Context) {
	var params outsideTradePayParams
	err := c.ShouldBindWith(&params, binding.FormPost)
	if err != nil {
		api.SendResponse(c, err, nil)
		return
	}
	uid, _ := service.GetUserIdByRequest(c)
	//userInfo, err := service.GetUserInfo(uid)
	//if err != nil {
	//	api.SendResponse(c, err, nil)
	//	return
	//}
	//ok := service.IsPayPasswordChecked(uid, params.U)
	//if !ok {
	//	api.SendResponse(c, errno.SignError, nil)
	//	return
	//}
	//if errValid := service.ValidateCode(userInfo.PhoneNumber, service.SendCodeScenetokenBuy, params.Code); errValid != nil {
	//	api.SendResponse(c, errValid, nil)
	//	return
	//}

	err = service.OutsideTradePay(params.OrderNo, uid)
	if err != nil {
		api.SendResponse(c, err, nil)
		return
	}
	//重置验证码
	//service.DeleteCodeCahce(userInfo.PhoneNumber, service.SendCodeScenetokenBuy)

	errno.OK.Info = "ok"
	api.SendResponse(c, errno.OK, nil)
	return
}

//订单详情
//Auth: Xu
func buyTradeInfo(c *gin.Context) {

}

//官方回购第一步（填写数量）
//Auth: Xu
func buybackStepFirst(c *gin.Context) {
	uid, _ := service.GetUserIdByRequest(c)
	//查询自有闲置令牌数量
	num, err := service.GetMyselfTokenUnusedNum(uid)
	if err != nil {
		api.SendResponse(c, err, nil)
		return
	}
	//查询令牌价格
	tokenNewCvntPrice := service.GetCurrentTokenCvntPrice(0)
	tokenOldCvntPrice := service.GetCurrentTokenCvntPrice(service.TokenOldBatch)
	returnData := make(map[string]interface{})
	returnData["haveOldNum"] = num.Old
	returnData["oldUnitPrice"] = tokenOldCvntPrice
	returnData["haveNewNum"] = num.New
	returnData["newUnitPrice"] = tokenNewCvntPrice

	restNum, rankNum, err := service.GetTodayRestBuyBackNum()
	if err != nil {
		api.SendResponse(c, err, nil)
		return
	}
	returnData["restNum"] = restNum
	returnData["rankNum"] = rankNum

	//用户今日剩余可回购令牌数量
	userTodayRestNum, err := service.GetUserTodayRestBuyBackNum(uid)
	if err != nil {
		api.SendResponse(c, err, nil)
		return
	}
	returnData["userTodayRestNum"] = userTodayRestNum

	errno.OK.Info = "ok"
	api.SendResponse(c, errno.OK, returnData)
	return
}

type buybackStepSecondParams struct {
	Num int `form:"num" json:"num" binding:"required"`
}

//官方回购第二步（确认回购信息）
//Auth: Xu
func buybackStepSecond(c *gin.Context) {
	// 检查参数是否为空
	var params buybackStepSecondParams
	err := c.ShouldBindWith(&params, binding.FormPost)
	if err != nil {
		api.SendResponse(c, err, nil)
		return
	}
	uid, _ := service.GetUserIdByRequest(c)
	err, returnData := service.TokenBuybackCreateOrder(uid, params.Num)
	if err != nil {
		api.SendResponse(c, err, nil)
		return
	}

	errno.OK.Info = "ok"
	api.SendResponse(c, errno.OK, returnData)
	return
}

type buybackStepThirdParams struct {
	OrderNo string `form:"orderNo" json:"orderNo" binding:"required,excludes=  "`
	Code    int    `form:"code" json:"code" binding:""`
	U       string `form:"u" json:"u" binding:"required,excludes= "`
}

//官方回购第三步（回购完成）
//Auth: Xu
func buybackStepThird(c *gin.Context) {
	var params buybackStepThirdParams
	err := c.ShouldBindWith(&params, binding.FormPost)
	if err != nil {
		api.SendResponse(c, err, nil)
		return
	}
	uid, _ := service.GetUserIdByRequest(c)
	userInfo, err := service.GetUserInfo(uid)
	if err != nil {
		api.SendResponse(c, err, nil)
		return
	}
	ok := service.IsPayPasswordChecked(uid, params.U)
	if !ok {
		api.SendResponse(c, errno.SignError, nil)
		return
	}
	if errValid := service.ValidateCode(userInfo.PhoneNumber, service.SendCodeScenetokenSale, params.Code); errValid != nil {
		api.SendResponse(c, errValid, nil)
		return
	}

	returnData, err := service.BuybackOrderSubmit(params.OrderNo, uid)
	if err != nil {
		api.SendResponse(c, err, nil)
		return
	}
	//重置验证码
	service.DeleteCodeCahce(userInfo.PhoneNumber, service.SendCodeScenetokenSale)

	errno.OK.Info = "ok"
	api.SendResponse(c, errno.OK, returnData)
	return
}

//查询自有闲置可出售令牌数量
//Auth: Xu
func selfNum(c *gin.Context) {
	uid, _ := service.GetUserIdByRequest(c)
	num, err := service.GetMyselfTokenUnusedNum(uid)
	if err != nil {
		api.SendResponse(c, err, nil)
		return
	}

	data := make(map[string]int)
	data["haveNum"] = num.New

	errno.OK.Info = "ok"
	api.SendResponse(c, errno.OK, data)
	return
}

type issueOrderParams struct {
	Num       int     `form:"num" json:"num" binding:"required"`
	UnitPrice float64 `form:"unitPrice" json:"unitPrice" binding:"required"`
	Code      int     `form:"code" json:"code"`
	U         string  `form:"u" json:"u" binding:"required,excludes= "`
}

//发布令牌出售订单
//Auth: Xu
func issueOrder(c *gin.Context) {
	var params issueOrderParams
	err := c.ShouldBindWith(&params, binding.FormPost)
	if err != nil {
		api.SendResponse(c, err, nil)
		return
	}
	uid, _ := service.GetUserIdByRequest(c)

	userInfo, err := service.GetUserInfo(uid)
	if err != nil {
		api.SendResponse(c, err, nil)
		return
	}
	ok := service.IsPayPasswordChecked(uid, params.U)
	if !ok {
		api.SendResponse(c, errno.SignError, nil)
		return
	}
	if errValid := service.ValidateCode(userInfo.PhoneNumber, service.SendCodeScenetokenSale, params.Code); errValid != nil {
		api.SendResponse(c, errValid, nil)
		return
	}
	//只允许保留两位小数
	priceStr := strconv.FormatFloat(params.UnitPrice, 'f', 2, 64)
	unitPrice, _ := strconv.ParseFloat(priceStr, 64)

	orderNo, err := service.IssueTokenUsdtOrder(uid, params.Num, unitPrice)
	if err != nil {
		api.SendResponse(c, err, nil)
		return
	}
	//重置验证码
	service.DeleteCodeCahce(userInfo.PhoneNumber, service.SendCodeScenetokenSale)

	data := make(map[string]interface{})
	data["orderNo"] = orderNo

	errno.OK.Info = "ok"
	api.SendResponse(c, errno.OK, data)
	return
}

type sellTradeInfoParams struct {
	OrderNo string `form:"orderNo"  binding:"required"`
}

//发布出售订单的详情
//Auth: Xu
func sellTradeInfo(c *gin.Context) {
	var params sellTradeInfoParams
	err := c.ShouldBindWith(&params, binding.FormPost)
	if err != nil {
		api.SendResponse(c, err, nil)
		return
	}
	uid, _ := service.GetUserIdByRequest(c)
	returnData, err := service.GetOrderInfo(params.OrderNo, uid)
	if err != nil {
		api.SendResponse(c, err, nil)
		return
	}

	errno.OK.Info = "ok"
	api.SendResponse(c, errno.OK, returnData)
	return
}

type saleOrderCancelParams struct {
	OrderNo string `form:"orderNo"  binding:"required"`
}

//售卖订单撤销
//Auth: Xu
func saleOrderCancel(c *gin.Context) {
	var params saleOrderCancelParams
	err := c.ShouldBindWith(&params, binding.FormPost)
	if err != nil {
		api.SendResponse(c, err, nil)
		return
	}
	uid, _ := service.GetUserIdByRequest(c)
	err = service.SaleOrderCancel(params.OrderNo, uid)
	if err != nil {
		api.SendResponse(c, err, nil)
		return
	}

	errno.OK.Info = "ok"
	api.SendResponse(c, errno.OK, nil)
	return
}

//我出售的订单列表
//Auth:Xu
func mySaleTradeList(c *gin.Context) {
	var params = model.NewDefaultPageParams()
	err := c.ShouldBindWith(&params, binding.Query)
	if err != nil {
		api.SendResponse(c, err, nil)
		return
	}
	uid, _ := service.GetUserIdByRequest(c)
	returnData, err := service.GetMySaleOrderList(uid, params.Per, params.Page)
	if err != nil {
		api.SendResponse(c, err, nil)
		return
	}

	errno.OK.Info = "ok"
	api.SendResponse(c, errno.OK, returnData)
	return
}

//租借广场
//Auth:Xu
func rentSquare(c *gin.Context) {
	var params = model.NewDefaultPageParams()
	err := c.ShouldBindWith(&params, binding.Query)
	if err != nil {
		api.SendResponse(c, err, nil)
		return
	}

	list, err := service.GetRentList(params.Per, params.Page)
	if err != nil {
		api.SendResponse(c, err, nil)
		return
	}

	errno.OK.Info = "ok"
	api.SendResponse(c, errno.OK, list)
	return
}

//我的发布
//Auth:Xu
func rentMyOrder(c *gin.Context) {
	var params = model.NewDefaultPageParams()
	err := c.ShouldBindWith(&params, binding.Query)
	if err != nil {
		api.SendResponse(c, err, nil)
		return
	}
	uid, _ := service.GetUserIdByRequest(c)
	list, err := service.GetMyRentList(uid, params.Per, params.Page)
	if err != nil {
		api.SendResponse(c, err, nil)
		return
	}

	errno.OK.Info = "ok"
	api.SendResponse(c, errno.OK, list)
	return
}

type rentOrderDetailParams struct {
	OrderNo string `form:"orderNo", binding:"required"`
}

//租借订单详情
//Auth:Xu
func rentOrderDetail(c *gin.Context) {
	var params rentOrderDetailParams
	err := c.ShouldBindWith(&params, binding.Query)
	if err != nil {
		api.SendResponse(c, err, nil)
		return
	}
	uid, _ := service.GetUserIdByRequest(c)
	info, err := service.GetMyRentOrderInfo(uid, params.OrderNo)
	if err != nil {
		api.SendResponse(c, err, nil)
		return
	}

	errno.OK.Info = "ok"
	api.SendResponse(c, errno.OK, info)
	return
}

//令牌租赁-出租令牌
//Author: TXG
func rentToken(c *gin.Context) {
	var (
		postData model.RentToken
	)
	//获取post参数
	if err := c.ShouldBindWith(&postData, binding.FormPost); err != nil {
		api.SendResponse(c, errno.ParamsError, nil)
		return
	}
	uid, _ := service.GetUserIdByRequest(c)
	orderNo, err := service.RentToken(uid, postData)
	if err != nil {
		api.SendResponse(c, err, nil)
		return
	}
	data := make(map[string]string)
	data["orderNo"] = orderNo
	errno.OK.Info = "OK"
	api.SendResponse(c, errno.OK, data)
	return
}

//令牌租赁-发布订单
//Author: TXG
func rentSubmitOrder(c *gin.Context) {
	var (
		postData model.RentSubmitOrderRequest
	)
	if err := c.ShouldBindWith(&postData, binding.FormPost); err != nil {
		api.SendResponse(c, errno.ParamsError, nil)
		return
	}
	uid, _ := service.GetUserIdByRequest(c)
	orderNo, err := service.RentSubmitOrder(uid, postData)
	if err != nil {
		api.SendResponse(c, err, nil)
		return
	}
	data := make(map[string]string)
	data["orderNo"] = orderNo
	errno.OK.Info = "OK"
	api.SendResponse(c, errno.OK, data)
	return
}

//令牌租赁-取消订单
//Author: TXG
func rentCancelOrder(c *gin.Context) {
	var (
		getData model.RentCancelOrder
	)
	//获取get参数
	if err := c.ShouldBindWith(&getData, binding.Query); err != nil {
		api.SendResponse(c, errno.ParamsError, nil)
		return
	}
	orderNo := getData.OrderNo
	uid, _ := service.GetUserIdByRequest(c)
	ok, err := service.RentCancelOrder(uid, orderNo)
	if err != nil {
		api.SendResponse(c, err, nil)
		return
	}
	if !ok {
		api.SendResponse(c, errno.InternError, nil)
		return
	}
	errno.OK.Info = "OK"
	api.SendResponse(c, errno.OK, nil)
	return
}

//令牌租赁-违规次数
//Author: TXG
func rentViolationNum(c *gin.Context) {
	uid, _ := service.GetUserIdByRequest(c)
	num, err := service.GetBadRecords(uid)
	if err != nil {
		api.SendResponse(c, err, nil)
		return
	}
	data := make(map[string]int64)
	data["num"] = num
	errno.OK.Info = "OK"
	api.SendResponse(c, errno.OK, data)
	return
}

//令牌租赁-检查保证金
//Author: TXG
func rentCheckDeposit(c *gin.Context) {
	var (
		getData model.RentCheckDeposit
	)
	uid, _ := service.GetUserIdByRequest(c)
	//获取get参数
	if err := c.ShouldBindWith(&getData, binding.Query); err != nil {
		api.SendResponse(c, errno.ParamsError, nil)
		return
	}
	num := getData.Num
	ok, data, err := service.RentCheckDeposit(uid, num)
	if err != nil {
		api.SendResponse(c, err, nil)
		return
	}
	if !ok {
		api.SendResponse(c, errno.PledgedUnEnoughErr, data)
		return
	}
	errno.OK.Info = "OK"
	api.SendResponse(c, errno.OK, nil)
}

func notRentNum(c *gin.Context) {
	uid, _ := service.GetUserIdByRequest(c)
	num, err := service.NotRentNum(uid)
	if err != nil {
		api.SendResponse(c, err, nil)
		return
	}
	data := make(map[string]int64)
	data["num"] = num
	errno.OK.Info = "OK"
	api.SendResponse(c, errno.OK, data)
}

//查询回购排队列表
//Auth:Xu
func myBuyBackQueue(c *gin.Context) {
	uid, _ := service.GetUserIdByRequest(c)
	returnData, err := service.GetMyBuybackQueueList(uid)
	if err != nil {
		api.SendResponse(c, err, nil)
		return
	}

	errno.OK.Info = "ok"
	api.SendResponse(c, errno.OK, returnData)
	return
}

type buyBackRankCancelParams struct {
	OrderNo string `form:"orderNo", binding:"required"`
}

//回购排队撤销
//Auth:Xu
func buyBackRankCancel(c *gin.Context) {
	var params buyBackRankCancelParams
	err := c.ShouldBindWith(&params, binding.FormPost)
	if err != nil {
		api.SendResponse(c, err, nil)
		return
	}
	uid, _ := service.GetUserIdByRequest(c)
	err = service.BuybackQueueCancel(uid, params.OrderNo)
	if err != nil {
		api.SendResponse(c, err, nil)
		return
	}

	errno.OK.Info = "ok"
	api.SendResponse(c, errno.OK, nil)
	return
}

func buyBackRankInfo(c *gin.Context) {
	uid, _ := service.GetUserIdByRequest(c)
	userRankNum, haveDealNum, rankNum, err := service.GetUserBuybackRankInfo(uid)
	if err != nil {
		api.SendResponse(c, err, nil)
		return
	}
	data := make(map[string]int, 0)
	data["userRankNum"] = userRankNum
	data["haveDealNum"] = haveDealNum
	data["rankNum"] = rankNum

	errno.OK.Info = "ok"
	api.SendResponse(c, errno.OK, data)
	return
}

//矿工平均收益
//Author: TXG
func minerAverageRevenue(c *gin.Context) {
	uid, _ := service.GetUserIdByRequest(c)
	averageRevenue, err := service.MinerAverageRevenue(uid)
	if err != nil {
		api.SendResponse(c, err, nil)
		return
	}
	data := make(map[string]float64)
	data["averageRevenue"] = averageRevenue
	errno.OK.Info = "OK"
	api.SendResponse(c, errno.OK, data)
}
